package windelpdv;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import javax.swing.JOptionPane;
import javax.swing.SwingConstants;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;

/**
 *
 * @author Marcio
 */
public class dlgLocalizaProduto extends javax.swing.JDialog {

    Dimension tela = Toolkit.getDefaultToolkit().getScreenSize();
    private Connection ConexaoWindel = null;
    private ResultSet rsWindel = null;
    String i = "7891024186244";
    protected boolean dadosAlterados;
    

    public dlgLocalizaProduto(java.awt.Frame parent, boolean modal, Connection conexaoWindel) {
        super(parent, modal);
        this.ConexaoWindel = conexaoWindel;
        initComponents();
        tfLocalizar.grabFocus();
        setSize(600, 600); //ponha aqui suas medidas  
        setLocation((tela.width - this.getSize().width) / 2, (tela.height - this.getSize().height) / 2);
        defineRenderers();
    }

    

    private void defineRenderers() {
        DefaultTableCellRenderer rendererCentro = new DefaultTableCellRenderer();
        rendererCentro.setHorizontalAlignment(SwingConstants.CENTER);
        DefaultTableCellRenderer rendererDireita = new DefaultTableCellRenderer();
        rendererDireita.setHorizontalAlignment(SwingConstants.RIGHT);
        DefaultTableCellRenderer rendererEsquerda = new DefaultTableCellRenderer();
        rendererEsquerda.setHorizontalAlignment(SwingConstants.LEFT);

        JTableHeader header = tbProdutos.getTableHeader();
        header.setPreferredSize(new Dimension(0, 15));
        TableColumnModel modeloDaColuna = tbProdutos.getColumnModel();

        modeloDaColuna.getColumn(0).setCellRenderer(rendererCentro);
        modeloDaColuna.getColumn(1).setCellRenderer(rendererEsquerda);
        modeloDaColuna.getColumn(2).setCellRenderer(rendererCentro);
        modeloDaColuna.getColumn(3).setCellRenderer(rendererCentro);


        modeloDaColuna.getColumn(0).setMaxWidth(400);
        modeloDaColuna.getColumn(1).setMaxWidth(1500);
        modeloDaColuna.getColumn(2).setMaxWidth(120);
        modeloDaColuna.getColumn(3).setMaxWidth(700);

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup1 = new javax.swing.ButtonGroup();
        jScrollPane1 = new javax.swing.JScrollPane();
        tbProdutos = new javax.swing.JTable();
        tfLocalizar = new javax.swing.JTextField();
        tfLocalizar.setDocument(new UpperCaseDocument());
        rbDescricao = new javax.swing.JRadioButton();
        rbBarras = new javax.swing.JRadioButton();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Localizar Produto");

        tbProdutos.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Código de Barras", "Descrição", "Preço", "Quantidade"
            }
        ));
        tbProdutos.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbProdutosMouseClicked(evt);
            }
        });
        tbProdutos.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tbProdutosKeyPressed(evt);
            }
        });
        jScrollPane1.setViewportView(tbProdutos);

        tfLocalizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tfLocalizarActionPerformed(evt);
            }
        });
        tfLocalizar.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                tfLocalizarFocusLost(evt);
            }
        });
        tfLocalizar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tfLocalizarKeyPressed(evt);
            }
        });

        buttonGroup1.add(rbDescricao);
        rbDescricao.setSelected(true);
        rbDescricao.setText("Descrição");
        rbDescricao.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                rbDescricaoFocusLost(evt);
            }
        });

        buttonGroup1.add(rbBarras);
        rbBarras.setText("Código de Barras");
        rbBarras.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                rbBarrasFocusLost(evt);
            }
        });

        jLabel1.setText("Produto");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(tfLocalizar)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 140, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(rbDescricao)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(rbBarras)
                .addGap(38, 38, 38))
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 342, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(tfLocalizar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(rbDescricao)
                    .addComponent(rbBarras))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tfLocalizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tfLocalizarActionPerformed
        Statement st;
        DefaultTableModel dtm = new DefaultTableModel(null, new String[]{"Código de Barras", "Descrição", "Preço", "Estoque"});
        try {
            st = ConexaoWindel.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

            if (rbDescricao.isSelected()) {
                rsWindel = st.executeQuery("Select BARRAS, DESCRICAO, VLR_VENDA, EST_ATUAL from produtos WHERE DESCRICAO like\'%" + tfLocalizar.getText() + "%\'order by DESCRICAO");
                while (rsWindel.next()) {
                    
                    ItemSelecionado item = new ItemSelecionado();
                    item.setCodBarras(rsWindel.getString("BARRAS"));
                    item.setDescricao(rsWindel.getString("DESCRICAO"));
                    item.setPrecoUnit(rsWindel.getString("VLR_VENDA"));
                    item.setEstoque(rsWindel.getString("EST_ATUAL"));
                    
                    dtm.addRow(new String [] {item.getCodBarras(), item.getDescricao(), item.getPrecoUnit(), item.getEstoque()}); 
                    //dtm.addRow(new String[]{rsWindel.getString("BARRAS"), rsWindel.getString("DESCRICAO"), rsWindel.getString("VLR_VENDA"), rsWindel.getString("EST_ATUAL")});
                }
            }

            if (rbBarras.isSelected()) {
                rsWindel = st.executeQuery("Select BARRAS, DESCRICAO, VLR_VENDA, EST_ATUAL from produtos WHERE BARRAS =\'" + tfLocalizar.getText() + "\'");
                while (rsWindel.next()) {
                    
                    ItemSelecionado item = new ItemSelecionado();
                    item.setCodBarras(rsWindel.getString("BARRAS"));
                    item.setDescricao(rsWindel.getString("DESCRICAO"));
                    item.setPrecoUnit(rsWindel.getString("VLR_VENDA"));
                    item.setEstoque(rsWindel.getString("EST_ATUAL"));
                    
                    dtm.addRow(new String [] {item.getCodBarras(), item.getDescricao(), item.getPrecoUnit(), item.getEstoque()}); 
                    //dtm.addRow(new String[]{rsWindel.getString("BARRAS"), rsWindel.getString("DESCRICAO"), rsWindel.getString("VLR_VENDA"), rsWindel.getString("EST_ATUAL")});

                }
            }         
            
            if (dtm.getRowCount() > 0) {
                tbProdutos.grabFocus();                
                tbProdutos.setModel(dtm);
                tbProdutos.setRowSelectionInterval(0, 0);
                defineRenderers();
                
            }
            /*
             * String n = /* ((String)
             * tbFornecedores.getValueAt(tbFornecedores.getSelectedRow(), 0));
             * detalharRegistro(n); tbFornecedores.grabFocus();
             * defineRenderers();
             */
            // }
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "Não foram encontrados Registros!", "Erro", JOptionPane.INFORMATION_MESSAGE);
        }
    }//GEN-LAST:event_tfLocalizarActionPerformed

    private void tbProdutosKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbProdutosKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
               String BarrasItemSel = (String) tbProdutos.getValueAt(tbProdutos.getSelectedRow(), 0);
               setBarras(BarrasItemSel);
               dadosAlterados = true;
               setVisible(false);
            }
        if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
               this.dispose();
            }
    }//GEN-LAST:event_tbProdutosKeyPressed

    private void tfLocalizarFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_tfLocalizarFocusLost
         /*  if (rbBarras.isSelected()){
               rbDescricao.grabFocus();
           }else{
               rbBarras.grabFocus();
           }*/
    }//GEN-LAST:event_tfLocalizarFocusLost

    private void rbDescricaoFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_rbDescricaoFocusLost
           tfLocalizar.grabFocus();
    }//GEN-LAST:event_rbDescricaoFocusLost

    private void rbBarrasFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_rbBarrasFocusLost
           tfLocalizar.grabFocus();
    }//GEN-LAST:event_rbBarrasFocusLost

    private void tfLocalizarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tfLocalizarKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ESCAPE) {
               this.dispose();
            }
        if (evt.getKeyCode() == KeyEvent.VK_F4) {
                tfLocalizarActionPerformed(null);
            }
    }//GEN-LAST:event_tfLocalizarKeyPressed

    private void tbProdutosMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbProdutosMouseClicked
        String BarrasItemSel = (String) tbProdutos.getValueAt(tbProdutos.getSelectedRow(), 0);
               setBarras(BarrasItemSel);
               dadosAlterados = true;
               setVisible(false);
    }//GEN-LAST:event_tbProdutosMouseClicked
    
    public String getFormatDec(String snumero) {
        snumero = snumero.replaceAll(",", ".");
        DecimalFormat df = new DecimalFormat("0.00");
        snumero = df.format(Double.parseDouble(snumero));
        snumero = snumero.replaceAll(",", ".");
        return snumero;
    }
    
    public boolean alterarDados()    
    {        
        dadosAlterados = false;  //Marcamos que o dados 
        setModal(true);         //A dialog tem que ser modal. Só pode retornar do setVisible após ficar invisível.
        setVisible(true);       //Mostramos a dialog e esperamos o usuário escolher alguma coisa.
        return dadosAlterados;   //Retornamos true, se ele pressionou ok.
    }
    
    public String getBarras() {
        return i;
    }
    
    public void setBarras(String i) {
        this.i = i;
    }
    
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup buttonGroup1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JRadioButton rbBarras;
    private javax.swing.JRadioButton rbDescricao;
    private javax.swing.JTable tbProdutos;
    private javax.swing.JTextField tfLocalizar;
    // End of variables declaration//GEN-END:variables
}
